package br.com.felix.fwt.ui;

import java.io.PrintWriter;

import org.apache.log4j.Logger;

import br.com.felix.fwt.log.LoggerFactory;
import br.com.felix.fwt.ui.css.PixelSize;
import br.com.felix.fwt.ui.css.Size;
import br.com.felix.fwt.ui.exception.ComponentRenderException;
import br.com.felix.fwt.util.IdGenerator;

/**
 * The Class LabeledTextBox is used to render a label and a textbox, since
 * this is a very common use of textboxes.
 */
public class LabeledTextBox extends BaseComponent{
	
	private static final long serialVersionUID = 9142207319625655561L;
	
	private static Logger logger = LoggerFactory.getLogger(LabeledTextBox.class);

	/** The label. */
	private String label;
	
	/** The label width. */
	public Size labelWidth;
	
	/** The txt box. */
	public TextBox txtBox;
	
	/**
	 * Instantiates a new labeled text box.
	 * 
	 * @param label the label
	 * @param value the value
	 */
	public LabeledTextBox(String label, String value){
		txtBox = new TextBox(value);
		this.label = label;
		this.labelWidth = new PixelSize(60);
		this.cssClass = "fwtlabeledtextbox";
	}
	
	
	/**
	 * Instantiates a new labeled text box.
	 * 
	 * @param label the label
	 */
	public LabeledTextBox(String label){
		this(label, "");
	}

	/* (non-Javadoc)
	 * @see br.com.felix.fwt.ui.BaseComponent#write(java.io.PrintWriter)
	 */
	public void write(PrintWriter out) throws ComponentRenderException {
		if(!authorized()) return;
		out.write("\n<div id=\"div_");
		out.write(getName());
		out.write("\" class=\"");
		out.write(cssClass);
		out.write("\" ");
		if(style!=null){
			out.write(style);
		}
		else{
			logger.warn("LabeledTextBox may not display correctly on Firefox.");
		}
		out.write(">\n<div id=\"label_");
		out.write(getName());
		out.write("\" style=\"float:left; width:");
		out.write(String.valueOf(labelWidth));
		out.write("\">");
		out.write(label);
		out.write("\n</div>\n<div>");
		txtBox.write(out);
		out.write("\n</div>\n</div>");
	}

	@Override
	public void setValue(String newValue) {
		txtBox.setValue(newValue);
	}

	/**
	 * @see BaseComponent#isInputControl()
	 * */
    @Override
    public boolean isInputControl() {
        return true;
    }

    @Override
    public String getValue() {
        return txtBox.getValue();
    }

    @Override
	public void generateName(IdGenerator idGen) {
		txtBox.generateName(idGen);
	}


	@Override
    public String getName() {
        return txtBox.getName();
    }


	@Override
	public void setName(String name) {
		txtBox.setName(name);
	}
	
}
